#include <QtGui>
#include <QtSql>

#include "databasemonitor.h"

DatabaseMonitor::DatabaseMonitor(const QString &tableName, QWidget *parent)
     : QDialog(parent)
 {
     createConnection();
     selectedRow = 0;

     model = new QSqlTableModel(this);
     model->setTable(tableName);
     model->setEditStrategy(QSqlTableModel::OnManualSubmit);

     model->select();

     model->setHeaderData(0, Qt::Horizontal, tr("Name"));
     model->setHeaderData(1, Qt::Horizontal, tr("Password"));
     model->setHeaderData(2, Qt::Horizontal, tr("Status"));

     QTableView *view = new QTableView;
     view->setModel(model);

     openButton = new QPushButton(tr("Open"));
     openButton->setDefault(true);
     saveButton = new QPushButton(tr("Save"));
     saveButton->setDefault(true);
     delButton = new QPushButton(tr("Delete row"));
     delButton->setDefault(true);
     revertButton = new QPushButton(tr("Revert"));
     quitButton = new QPushButton(tr("Quit"));

     buttonBox = new QDialogButtonBox(Qt::Vertical);

     buttonBox->addButton(openButton, QDialogButtonBox::ActionRole);
     buttonBox->addButton(saveButton, QDialogButtonBox::ActionRole);
     buttonBox->addButton(delButton, QDialogButtonBox::ActionRole);
     buttonBox->addButton(revertButton, QDialogButtonBox::ActionRole);
     buttonBox->addButton(quitButton, QDialogButtonBox::RejectRole);

     connect(openButton, SIGNAL(clicked()), this, SLOT(open()));
     connect(saveButton, SIGNAL(clicked()), this, SLOT(submit()));
     connect(delButton, SIGNAL(clicked()), this, SLOT(del()));
     connect(revertButton, SIGNAL(clicked()), model, SLOT(revertAll()));
     connect(quitButton, SIGNAL(clicked()), this, SLOT(close()));

     connect(view, SIGNAL(clicked(QModelIndex)), this, SLOT(selected(QModelIndex)));
     connect(model, SIGNAL(dataChanged(QModelIndex,QModelIndex)), this, SLOT(entered(QModelIndex,QModelIndex)));

     QHBoxLayout *mainLayout = new QHBoxLayout;
     mainLayout->addWidget(view);
     mainLayout->addWidget(buttonBox);
     setLayout(mainLayout);

     setWindowTitle(tr("MSG DB"));

     setMinimumSize(500,300);
 }

void DatabaseMonitor::open()
{
    fileName = QFileDialog::getOpenFileName(this, tr("Open Database File"),
                                            QDir::currentPath(),
                                            tr("Database files (*.dat)"));
    if (fileName.isEmpty())
        return;

    QFile file(fileName);
    if (!file.exists())
        return;

    if (changeConnection()) {
        submit();
    }
}

void DatabaseMonitor::entered(QModelIndex qMIndex1,QModelIndex qMIndex2)
{
    //
}

void DatabaseMonitor::selected(QModelIndex qMIndex)
{
    selectedRow = qMIndex.row();
}

 void DatabaseMonitor::submit()
 {
     model->database().transaction();
     if (model->submitAll()) {
         model->database().commit();
     } else {
         model->database().rollback();
         QMessageBox::warning(this, tr("MSG DB"),
                              tr("The database reported an error: %1")
                              .arg(model->lastError().text()));
     }
 }

 void DatabaseMonitor::del()
 {
     model->database().transaction();
     if (model->removeRow(selectedRow)) {
         model->database().commit();
     } else {
         model->database().rollback();
         QMessageBox::warning(this, tr("MSG DB"),
                              tr("The database reported an error: %1")
                              .arg(model->lastError().text()));
     }
 }

 bool DatabaseMonitor::createConnection()
 {
     QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE");
     db.setDatabaseName(":memory:");
     if (!db.open()) {
         QMessageBox::critical(0, qApp->tr("Cannot open database"),
             qApp->tr("Unable to establish a database connection.\n"
                      "This example needs SQLite support. Please read "
                      "the Qt SQL driver documentation for information how "
                      "to build it.\n\n"
                      "Click Cancel to exit."), QMessageBox::Cancel);
         return false;
     }

     QSqlQuery query;
     query.exec("create table users (name varchar(32), "
                                    "pass varchar(40), "
                                    "status int)");
     query.exec("insert into users values('Please select', 'db to edit.', 1)");
     return true;
 }

 bool DatabaseMonitor::changeConnection()
 {
     QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE");
     db.setDatabaseName(fileName);

     if (!db.open()) {
         QMessageBox::warning(this, tr("Wrong file"),
                              tr("Cannot read db from given file."));
         return false;
     }

     return true;
 }
